<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\WechatLoginRequest;
use App\Services\WechatAuthService;
use App\Services\WechatAuthServiceMock;
use App\Traits\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    use ApiResponse;

    protected $wechatAuthService;

    public function __construct(WechatAuthService $wechatAuthService, WechatAuthServiceMock $wechatAuthServiceMock)
    {
        // 根据环境选择使用真实或模拟服务
        $this->wechatAuthService = config('app.env') === 'production' 
            ? $wechatAuthService 
            : $wechatAuthServiceMock;
    }

    /**
     * 微信小程序登录
     */
    public function login(WechatLoginRequest $request): JsonResponse
    {
        try {
            $user = $this->wechatAuthService->login(
                $request->input('code'),
                $request->input('userInfo', [])
            );

            // 生成token
            $token = $user->createToken('api')->plainTextToken;

            return $this->success([
                'user' => $user,
                'token' => $token,
            ], '登录成功');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * Web管理后台登录
     */
    public function webLogin(\Illuminate\Http\Request $request)
    {
        try {
            $phone = $request->input('phone');
            $password = $request->input('password');
            
            // 验证手机号格式
            if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
                return redirect()->back()->withErrors(['phone' => '请输入正确的手机号']);
            }
            
            // 查找用户
            $user = \App\Models\User::where('phone', $phone)->first();
            if (!$user) {
                return redirect()->back()->withErrors(['phone' => '用户不存在']);
            }
            
            // 验证密码
            if (!$user->password || !\Illuminate\Support\Facades\Hash::check($password, $user->password)) {
                return redirect()->back()->withErrors(['password' => '密码错误']);
            }

            // 使用web guard登录
            Auth::guard('web')->login($user);

            return redirect()->route('admin.dashboard');

        } catch (\Exception $e) {
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
        }
    }


    /**
     * 获取当前用户信息
     */
    public function me(): JsonResponse
    {
        try {
            $user = Auth::user();
            
            if (!$user) {
                return $this->error('用户未登录', 401);
            }

            return $this->success([
                'user' => $user
            ], '获取用户信息成功');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 刷新token
     */
    public function refresh(): JsonResponse
    {
        try {
            $user = Auth::user();
            
            if (!$user) {
                return $this->error('用户未登录', 401);
            }

            // 删除当前token
            $user->currentAccessToken()->delete();

            // 生成新token
            $token = $user->createToken('api')->plainTextToken;

            return $this->success([
                'token' => $token
            ], 'Token刷新成功');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        try {
            // 检查是否是Web请求
            if (request()->expectsJson()) {
                // API请求，返回JSON
                $user = Auth::user();
                
                if ($user) {
                    $user->currentAccessToken()->delete();
                }

                return $this->success([], '退出登录成功');
            } else {
                // Web请求，重定向到登录页面
                Auth::guard('web')->logout();
                return redirect()->route('admin.login')->with('success', '已成功退出登录');
            }

        } catch (\Exception $e) {
            if (request()->expectsJson()) {
                return $this->handleException($e);
            } else {
                return redirect()->route('admin.login')->withErrors(['error' => '退出登录失败：' . $e->getMessage()]);
            }
        }
    }
}